package com.sky.service.impl;

import com.alibaba.druid.support.spring.stat.SpringStat;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Constant;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;

import org.apache.commons.lang.StringUtils;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;

    private Long orderId;
    @Autowired
    private WebSocketServer webSocketServer;


    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        //处理各种业务异常(地址簿为空,购物车数据为空)
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            //抛出业务异常
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);

        }
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() <= 0) {
            //查不到有这个人的购物车数据
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }


        //向订单表插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);//刚刚下单 所有还没有付款
        orders.setStatus(Orders.PENDING_PAYMENT);//
        orders.setNumber(String.valueOf(System.currentTimeMillis()));//将long 类型转换为字符串

        //通过地址簿得到电话和收货人
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());//consignee
        orders.setUserId(userId);
        //向订单表插入一条数据
        orderMapper.insert(orders);

        orderId = orders.getId();
        List<OrderDetail> orderDetailList = new ArrayList<>();
        //向订单明细表 插入n条数据
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();//订单明细
            BeanUtils.copyProperties(cart, orderDetail);
            //设置当前订单号
            orderDetail.setOrderId(orderId);
            orderDetailList.add(orderDetail);

        }
        //批量插入 订单明细表
        orderDetailMapper.insertBatch(orderDetailList);

        //清空购物车

        shoppingCartMapper.deleteByUserId(userId);

        //返回返回值
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()//不能简单的配置属性拷贝 得属性名一样才能拷贝
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .id(orders.getId())
                .build();

        return orderSubmitVO;


    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
/*        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

       //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );/*


        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));




        return vo;*/

        new Thread() {
            @Override
            public void run() {
                try {
                    sleep(30);
                    paySuccess(ordersPaymentDTO.getOrderNumber());

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }.start();
        //通过websocket来向客户端推送消息 type orderId content
        String orderNumber = ordersPaymentDTO.getOrderNumber();
        Orders ordersDB = orderMapper.getByNumber(orderNumber);

        Map map = new HashMap<>();
        map.put("type", 1);
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号:" + orderNumber);

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);

        return null;

    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .id(orderId)
                .build();

        orderMapper.update(orders);


    }


//    @Override
//    public OrderVO getHistoryOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
//        //根据page pageSize userId 查询订单表所有信息 加上  订单细节表所有信息
//        Long userId = BaseContext.getCurrentId();
//        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
//        //返回的是一个集合
//        ordersPageQueryDTO.setUserId(userId);
//        Page<Orders> page = orderMapper.page(ordersPageQueryDTO);
//        Orders orderDishes=new Orders();
//        long total = page.getTotal();
//        List<Orders> result = page.getResult();
//        for (Orders orderDish : result) {
//
//        }
//
//
//
//    }

    /**
     * 分页查询历史订单
     *
     * @param
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult getHistoryOrders(int pageNum, int pageSize, Integer status) {
        //获取谁的历史订单
        Long userId = BaseContext.getCurrentId();
        OrdersPageQueryDTO ordersPageQueryDTO = OrdersPageQueryDTO.builder()
                .status(status)
                .userId(userId)
                .build();
        PageHelper.startPage(pageNum, pageSize);
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList<>();

        //判断这个人有没有下过单
        if (page != null && page.getTotal() > 0) {
            //如果没有就将他的订单细节交给OrderVO
            for (Orders orders : page) {
                Long id = orders.getId();
                //
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

                OrderVO orderVO = new OrderVO();
                //订单信息交给VO
                BeanUtils.copyProperties(orders, orderVO);
                //订单细节交给VO
                orderVO.setOrderDetailList(orderDetailList);
                //
                list.add(orderVO);

            }

        }

        return new PageResult(page.getTotal(), list);


    }

    /**
     * 根据id查询订单情况和详情
     *
     * @Override
     */
    public OrderVO selectOrderDetail(Long id) {

        Orders orders = orderMapper.getById(id);


        //获取订单详情

        List<OrderDetail> orderDetail = orderDetailMapper.getByOrderId(orders.getId());
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetail);

        return orderVO;
    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Override
    public void cancel(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
//            //调用微信支付退款接口
//            weChatPayUtil.refund(
//                    ordersDB.getNumber(), //商户订单号
//                    ordersDB.getNumber(), //商户退款单号
//                    new BigDecimal(0.01),//退款金额，单位 元
//                    new BigDecimal(0.01));//原订单金额

            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }

        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void repetition(Long id) {
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);


    }

    @Override
    public PageResult page(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(page);

        return new PageResult(page.getTotal(), orderVOList);
    }

    @Override
    public OrderStatisticsVO countByStatus() {
        //根据状态统计    public static final Integer TO_BE_CONFIRMED = 2;//confirmed
        //    public static final Integer CONFIRMED = 3;
        //    public static final Integer DELIVERY_IN_PROGRESS = 4;
        //待接单数量 2
        Integer ordersToBeConfirmed = orderMapper.countByToBeConfirmed(Orders.TO_BE_CONFIRMED);

        //待派送数量 3
        Integer ordersConfirmed = orderMapper.countByConfirmed(Orders.CONFIRMED);

        //派送中数量 4
        Integer ordersDelivery = orderMapper.countByDeliveryInProgress(Orders.DELIVERY_IN_PROGRESS);

        //
        OrderStatisticsVO orderStatisticsVO = OrderStatisticsVO.builder()
                .confirmed(ordersConfirmed)
                .deliveryInProgress(ordersDelivery)
                .toBeConfirmed(ordersToBeConfirmed)
                .build();
        return orderStatisticsVO;
    }


    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）//map  的主要功能是对流中的元素
        // 进行转换处理，生成一个新的流，便于后续的数据处理和操作。
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    /**
     * 接单 根据id 改变status
     *
     * @param
     */
    @Override
    public void updateById(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        ordersConfirmDTO.setStatus(Orders.CONFIRMED);
        orders.setStatus(ordersConfirmDTO.getStatus());
        orders.setId(ordersConfirmDTO.getId());
        BeanUtils.copyProperties(ordersConfirmDTO, orders);
        orderMapper.update(orders);

    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        // 拒单 拒单原因 要有 得是待接单才能拒单
        // 拒单得退钱给人家

        Orders orders = orderMapper.getById(ordersRejectionDTO.getId());

        //退钱
        // 订单处于待接单状态下取消，需要进行退款
        if (orders != null && orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {

//            //调用微信支付退款接口
//            weChatPayUtil.refund(
//                    ordersDB.getNumber(), //商户订单号
//                    ordersDB.getNumber(), //商户退款单号
//                    new BigDecimal(0.01),//退款金额，单位 元
//                    new BigDecimal(0.01));//原订单金额

            //支付状态
            Integer payStatus = orders.getPayStatus();
            if (payStatus == Orders.PAID)
            //支付状态修改为 退款
            {
                orders.setPayStatus(Orders.REFUND);

                // 更新订单状态、取消原因、取消时间
                orders.setId(ordersRejectionDTO.getId());
                orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("商家取消");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        } else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
    }

    @Override
    public void cancelByStatus3And4(OrdersCancelDTO ordersCancelDTO) throws Exception {
        //待派送 3  派送中4  更新状态为6 已取消 并退款

        Long ordersCancelDTOId = ordersCancelDTO.getId();
        Orders orders = orderMapper.getById(ordersCancelDTOId);
        Integer status = orders.getStatus();
        String cancelReason = ordersCancelDTO.getCancelReason();
        Orders ordersNew = new Orders();
        if ((status == Orders.CONFIRMED || status == Orders.DELIVERY_IN_PROGRESS) && cancelReason != null) {
            //进行退款操作

            BeanUtils.copyProperties(orders, ordersNew);
            ordersNew.setCancelTime(LocalDateTime.now());
            ordersNew.setCancelReason(cancelReason);
            ordersNew.setPayStatus(Orders.REFUND);
            ordersNew.setStatus(Orders.CANCELLED);
            orderMapper.update(ordersNew);
        } else {
            new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

    }

    @Override
    public void delivery(Long id) {
        //订单派送 将状态改为 派送中 只有 待派送的才能改
        Orders orders = orderMapper.getById(id);
        Integer status = orders.getStatus();

        if (status != 3 || orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setId(id);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        //将状态改为已完成 且 只有状态为派送中才能改
        Orders orders = orderMapper.getById(id);
        Integer status = orders.getStatus();
        if (status != Orders.DELIVERY_IN_PROGRESS || orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.COMPLETED);
        orders.setId(id);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 客户催单
     *
     * @param id
     */
    @Override
    public void reminder(Long id) {
        //确认是否有这个订单
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Map map = new HashMap<>();
        map.put("type", 2);//1表示来单提醒 2表示 客户催单
        map.put("orderId", id);
        map.put("content", "订单号:" + orders.getNumber());

        //通过websocket来向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    @Override
    public OrderReportVO getOrderSatistics(LocalDate begin, LocalDate end) {
        //    //日期，以逗号分隔，例如：2022-10-01,2022-10-02,2022-10-03
        //    private String dateList;
        //
        //    //每日订单数，以逗号分隔，例如：260,210,215
        //    private String orderCountList;
        //
        //    //每日有效订单数，以逗号分隔，例如：20,21,10
        //    private String validOrderCountList;
        //
        //    //订单总数
        //    private Integer totalOrderCount;
        //
        //    //有效订单数
        //    private Integer validOrderCount;
        //
        //    //订单完成率
        //    private Double orderCompletionRate;
        //

        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> orderCountList=new ArrayList<>();
        List<Integer> validOrderCountList=new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime beginDate = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endDate = LocalDateTime.of(localDate, LocalTime.MAX);
            //获取每日总订单
            Integer orderTolal = getOrderCount(beginDate, endDate, null);
            //获取每日有效总订单
            Integer orderValid = getOrderCount(beginDate, endDate, 5);

            orderCountList.add(orderTolal);
            validOrderCountList.add(orderValid);
        }
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //考虑被除数 订单总量为0 的情况
        double orderCompletionRate=0.0;
        if (totalOrderCount!=0){
         orderCompletionRate=(double) validOrderCount/totalOrderCount;}
        return OrderReportVO.builder()
                .orderCompletionRate(orderCompletionRate)
                .totalOrderCount(totalOrderCount)
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCount(validOrderCount)
                .dateList(StringUtils.join(dateList,","))
                .build();


    }


    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end, Integer status) {
        Map map = new HashMap<>();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);
        return orderMapper.countMap(map);

    }

    /**
     * 统计指定时间内的销量前10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        //在细节表中查菜名 在订单表中查状态
        // select sum(od.number) number,od.name  from order_detail od and order o where od.order_id=o.id and status=5
        // and o.order_time> ? and o.order_time < ?
        // group by od.name order by number desc limit 0,10

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);

        List<String> name = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(name, ",");
        List<Integer> number = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(number, ",");

        return new SalesTop10ReportVO(nameList,numberList);

    }


/*
//自己写的方法
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        String join = StringUtils.join(dateList, ",");
        List<Integer> orderCountList=new ArrayList<>();
        List<Integer> validOrderCountList=new ArrayList<>();

        for (LocalDate localDate : dateList) {
            LocalDateTime beginDate = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endDate = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map=new HashMap<>();
            map.put("begin",beginDate);
//              不需要去sql查询 遍历每日数据后相加
//            //订单总数
//            Integer totalOrderCount=orderMapper.countMap(map);
//            //订单有效总数
//            map.put("status",Orders.COMPLETED);
//            Integer validOrderCount=orderMapper.countMap(map);
//            map.remove("status");
//

            map.put("end",endDate);
            //select count(id) from order where order_time(下单时间)>begin and order_time<(&lt;) end
            //每日订单数
            Integer orderCountEveryDay= orderMapper.countMap(map);
            //select ~~~and status =5
            map.put("status",Orders.COMPLETED);
            //每日有效订单数
            Integer validOrderCountEveryDay= orderMapper.countMap(map);
            orderCountList.add(orderCountEveryDay);
            validOrderCountList.add(validOrderCountEveryDay);

           // orderAllmap.put("订单总数",totalOrderCount);
           // orderAllmap.put("有效订单总数",validOrderCount);


        }

        int totalOrderCount=0;
        for (int i = 0; i < orderCountList.size(); i++) {
            totalOrderCount=orderCountList.get(i)+totalOrderCount;
        }
        int validOrderCount=0;
        for (int i = 0; i < validOrderCountList.size(); i++) {
            validOrderCount=validOrderCountList.get(i)+validOrderCount;
        }



        return OrderReportVO.builder()
                .dateList(join)
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate((double)validOrderCount/totalOrderCount)
                .build();

    }*/

//    /**
//     * 查询订单详细信息
//     *
//
//    */
//    public OrderVO queryDetail(Long id) {
//        Orders orders = orderMapper.getById(id);
//        OrderVO orderVO=new OrderVO();
//        BeanUtils.copyProperties(orders,orderVO);
//        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
//        orderVO.setOrderDetailList(orderDetailList);
//        return orderVO;
//
//    }
}


//        //业务规则
//        /*
//        - 待支付和待接单状态下，用户可直接取消订单
//- 商家已接单状态下，用户取消订单需电话沟通商家
//- 派送中状态下，用户取消订单需电话沟通商家
//- 如果在待接单状态下取消订单，需要给用户退款
//- 取消订单后需要将订单状态修改为“已取消”
//         */
//
//        //判断status状态 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
//
//        Orders order = orderMapper.getById(id);
//        //得进行判断订单是否存在
//        if(order==null){
//            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
//        }
//        Integer status = order.getStatus();
//        if (status==1||status==2){
//            if (status==2) {
//                // 不能删除啊  得修改 设置取消订单 取消订单原因 取消时间orderMapper.deleteById(id);
//                orderDetailMapper.deleteByOrderId(id);
//                //无法调用微信接口
//                order.setPayStatus(Orders.REFUND);//设置为已退款
//                //更新Order
//                order.setCancelReason("用户取消");
//                order.setCancelTime(LocalDateTime.now());
//                order.setStatus(Orders.CANCELLED);
//                //
//                orderMapper.update(order);
//            } else if (status==1) {
//                //更新Order
//                order.setCancelReason("用户取消");
//                order.setCancelTime(LocalDateTime.now());
//                order.setStatus(Orders.CANCELLED);
//                //
//                orderMapper.update(order);
//            }
//
//        } else if (status==3||status==4) {
//            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
//        }
//
//
//    }
